package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.to.es.EsSkuUpTo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.EsConfig;
import com.atguigu.gulimall.search.constant.IndexConstant;
import com.atguigu.gulimall.search.service.EsSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhuguanming
 * @description Es ServiceImpl
 * @date 2021/5/26 21:28
 */
@Service
@Slf4j
public class EsSearchServiceImpl implements EsSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public R bulkProduct(List<EsSkuUpTo> esSkuUpTos) {
        BulkRequest bulkRequest = new BulkRequest();
        esSkuUpTos.forEach(item -> {
            IndexRequest indexRequest = new IndexRequest(IndexConstant.PRODUCT_INDEX);
            indexRequest.id(String.valueOf(item.getSkuId()));
            indexRequest.source(JSON.toJSONString(item), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulkResponse;
        try {
            bulkResponse = restHighLevelClient.bulk(bulkRequest, EsConfig.COMMON_OPTIONS);
        } catch (Exception e) {
            log.error("批量保存sku数据异常：{}", e.getMessage(), e);
            return R.error(BizCodeEnum.PRODUCT_INDEX_EXCEPTION);
        }
        boolean hasFailures = bulkResponse.hasFailures();
        if (BooleanUtils.isTrue(hasFailures)) {
            log.error("EsSearchServiceImpl bulkProduct 保存数据失败：{}", bulkResponse.buildFailureMessage());
            return R.error(String.format("EsSearchServiceImpl bulkProduct 保存数据失败：%s", bulkResponse.buildFailureMessage()));
        }
        List<String> successIds = Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("EsSearchServiceImpl bulkProduct 保存数据成功：{}", successIds);
        return R.ok();
    }
}
